
#include "main.h"
#include "usb_config.h"

void usb_connect(void)
{
    gpio_bit_set(GPIOA, GPIO_PIN_8);
}

void usb_disconnect(void)
{
    gpio_bit_reset(GPIOA, GPIO_PIN_8);
}

void usbd_configure_done_callback(void)
{
    
}

void usb_dc_low_level_init(void)
{
    rcu_periph_clock_enable(RCU_GPIOA);
    /* enable the power clock */
    rcu_periph_clock_enable(RCU_PMU);
    /* configure USB model clock from PLL clock */
    rcu_usb_clock_config(RCU_CKUSB_CKPLL_DIV2);
    /* enable USB APB1 clock */
    rcu_periph_clock_enable(RCU_USBD);
    
    /* configure usb pull-up pin */
    gpio_init(GPIOA, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_8);
    usb_disconnect();
    /* USB wakeup EXTI line configuration */
    exti_interrupt_flag_clear(EXTI_18);
    exti_init(EXTI_18, EXTI_INTERRUPT, EXTI_TRIG_RISING);
    
    /* 1 bit for pre-emption priority, 3 bits for subpriority */
    nvic_priority_group_set(NVIC_PRIGROUP_PRE1_SUB3);
    /* enable the USB low priority interrupt */
    nvic_irq_enable((uint8_t)USBD_LP_CAN0_RX0_IRQn, 1U, 0U);
    /* enable the USB Wake-up interrupt */
    nvic_irq_enable((uint8_t)USBD_WKUP_IRQn, 0U, 0U);
    usb_connect();
}

void usb_dc_low_level_deinit(void)
{
    usb_disconnect();
    /* disable the USB low priority interrupt */
    nvic_irq_disable((uint8_t)USBD_LP_CAN0_RX0_IRQn);
    /* disable the USB Wake-up interrupt */
    nvic_irq_disable((uint8_t)USBD_WKUP_IRQn);
}


/*!
    \brief      this function handles USBD wakeup interrupt request.
    \param[in]  none
    \param[out] none
    \retval     none
*/
void USBD_WKUP_IRQHandler (void)
{
    exti_interrupt_flag_clear(EXTI_18);
}


